import { PageConfig } from 'next';
import anylogger from 'anylogger';
import '@mmstudio/an000042';
import an48 from '@mmstudio/an000048';
import { tbmajor } from '../../../../atoms/db';
import Guid from '../../../../atoms/guid';

const logger = anylogger('pages/api/basicinformation/major/update.api');

export type Result = {
	ok: boolean;
	message: string;
};

export type Message = ITbmajor;

/**
 * 专业管理-更新数据
 */
const handler = an48<Result>();

handler.post(async (req, res) => {
	try {
		logger.debug('msg body:', req.body);
		const { major_id, ...body } = req.body as Message;
		//#region 验证必填
		if (!body.majorname) {
			res.status(200).json({
				ok: false,
				message: '专业名称不能为空'
			});
			return;
		}
		if (!body.objectives) {
			res.status(200).json({
				ok: false,
				message: '人才培养目标不能为空！'
			});
			return;
		}
		if (!body.professionalprofile) {
			res.status(200).json({
				ok: false,
				message: '专业简介不能为空！'
			});
			return;
		}
		//#endregion
		//编辑
		if (major_id) {
			//专业名称是否存在
			const d = await tbmajor().select('*').where({
				majorname: body.majorname
			});
			if (d.find((it) => { return it.major_id !== major_id; })) {
				res.status(200).json({
					ok: false,
					message: '专业名称不能重复'
				});
				return;
			}
			await tbmajor().update(body).where({
				major_id
			});
		}
		//新增
		else {
			//专业名称是否存在
			const d = await tbmajor().first('*').where({
				majorname: body.majorname
			});
			if (d && d.majorname) {
				res.status(200).json({
					ok: false,
					message: '专业名称不能重复'
				});
				return;
			}
			await tbmajor().insert({
				...body,
				major_id: Guid()
			});
		}

		res.status(200).json({ ok: true, message: '' });
	} catch (error) {
		logger.error(error);
		logger.trace(error);
		res.status(200).json({ ok: false, message: (error as Error).message });
	}
});

export const config = {} as PageConfig;

export default handler;
